package cool.houge.demo.service;

import cool.houge.demo.entity.Employee;
import cool.houge.demo.repository.EmployeeRepository;
import io.ebean.annotation.Transactional;
import io.ebean.annotation.TxType;

/**
 * @author ZY (kzou227@qq.com)
 */
public class DemoService {

    private final EmployeeRepository employeeRepository;

    public DemoService(EmployeeRepository employeeRepository) {
        this.employeeRepository = employeeRepository;
    }

    @Transactional
    public void transactionalAnnotation() {
        System.out.println("transactional annotation");
        throw new RuntimeException();
    }

    // 嵌套事务测试
    @Transactional
    public void saveEmployees(Employee employee1, Employee employee2) {
        /*
         * 这里使用的 SQLite 作为测试数据库。SQLite 仅支持单事务操作，故将嵌套事务放置在前面执行。
         */
        this.nestedSaveEmployee(employee2);

        employeeRepository.save(employee1);
        throw new RuntimeException("manual exception");
    }

    @Transactional(type = TxType.REQUIRES_NEW)
    private void nestedSaveEmployee(Employee employee2) {
        employeeRepository.save(employee2);
    }
}
